package cn.cs.service.impl;

import cn.cs.client.RestCsImageClient;
import cn.cs.client.RestCsUserClient;
import cn.cs.common.BaseException;
import cn.cs.common.Constants;
import cn.cs.common.EmptyUtils;
import cn.cs.common.RedisUtils;
import cn.cs.exception.UserInfoErrorCode;
import cn.cs.pojo.CsImage;
import cn.cs.pojo.CsUser;
import cn.cs.service.CsUserInfoService;
import cn.cs.vo.CsUserVO;
import cn.cs.vo.QueryUserVo;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by yuexl
 */
@Service
public class CsUserInfoServiceImpl implements CsUserInfoService {
    private static final Logger logger = LoggerFactory.getLogger(CsUserInfoServiceImpl.class);
    @Resource
    private RestCsUserClient restCsUserClient;
    @Resource
    private RestCsImageClient restCsImageClient;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public QueryUserVo queryUserInfoById(Long id) throws Exception {
        //根据用户id查询用户信息
        CsUser csUser = restCsUserClient.getCsUserById(id);
        //如果用户不存在，则抛出异常
        if (EmptyUtils.isEmpty(csUser)) {
            logger.info("[queryUserInfoById]" + "获取用户信息失败，用户的id为：" + id);
            throw new BaseException(UserInfoErrorCode.USER_NO_EXISTS);
        }

        //获取用户头像图片地址
        List<CsImage> csImages = null;
        QueryUserVo queryUserVo = new QueryUserVo();
        //先从redis缓存中获取
        String key = Constants.IMAGE_TOKEN_PREFIX + id +
                "_" + Constants.Image.ImageType.normal +
                "_" + Constants.Image.ImageCategory.user;
        String imgUrl = (String) redisUtils.get(key);
        logger.info("[queryUserInfoById]" + "获取到的用户的头像图片为：" + imgUrl);
        //如果从reids缓存中没有获取到用户头像则从数据库中查询
        if (EmptyUtils.isEmpty(imgUrl)) {
            logger.info("[queryUserInfoById]" + "redis缓存中没有用户图片，用户id为：" + id);
            csImages = restCsImageClient.queryCsImageList(id, Constants.Image.ImageType.normal, Constants.Image.ImageCategory.user);
            //如果用户有头像
            if (csImages.size() != 0) {
                imgUrl = csImages.get(0).getImgUrl();
                queryUserVo.setImgUrl(imgUrl);
                //此时需要将此用户头像实时地放到redis缓存中
                redisUtils.set(key, imgUrl);
            }
        } else {
            queryUserVo.setImgUrl(imgUrl);
        }
        BeanUtils.copyProperties(csUser, queryUserVo);
        return queryUserVo;
    }

    @Override
    public Integer qdtxModifyCsUser(QueryUserVo queryUserVo) throws Exception {
        CsUser csUser = new CsUser();
        CsImage csImage = new CsImage();
        BeanUtils.copyProperties(queryUserVo, csUser);
        //查询dmImage
        List<CsImage> csImages = null;
        //根据用户id查询用户信息
        CsUser csUserFlag = restCsUserClient.getCsUserById(csUser.getId());
        //如果用户不存在，则抛出异常
        if (EmptyUtils.isEmpty(csUserFlag)) {
            logger.info("[qdtxModifyDmUser]" + "用户信息不存在：" + queryUserVo.getId());
            throw new BaseException(UserInfoErrorCode.USER_NO_EXISTS);
        }
        //修改用户信息
        int i = restCsUserClient.qdtxModifyCsUser(csUser);
        //判断用户是否修改了头像
        if (EmptyUtils.isNotEmpty(queryUserVo.getImgUrl()) && !(Constants.FILE_PRE + Constants.DEFAULT_USER).equals(queryUserVo.getImgUrl())) {
            logger.info("[qdtxModifyDmUser]" + "用户已经设置过头像：" + queryUserVo.getImgUrl());
            //先从redis缓存中查询
            String key = Constants.IMAGE_TOKEN_PREFIX + csUser.getId() +
                    "_" + Constants.Image.ImageType.normal +
                    "_" + Constants.Image.ImageCategory.user;
            csImages = restCsImageClient.queryCsImageList(csUser.getId(), Constants.Image.ImageType.normal, Constants.Image.ImageCategory.user);
            if (csImages.size() == 0 || null == csImages.get(0).getId()) {//如果该用户没有头像,不仅要更新用户表的头像图片，还要将头像添加到dm_image表
                csImage.setTargetId(queryUserVo.getId().intValue());
                csImage.setType(0);
                csImage.setImgUrl(queryUserVo.getImgUrl());
                csImage.setCategory(0);
                restCsImageClient.qdtxAddCsImage(csImage);
            } else {//修改头像信息
                csImage = csImages.get(0);
                csImage.setImgUrl(queryUserVo.getImgUrl());
                restCsImageClient.qdtxModifyCsImage(csImage);
            }
            //修改redis缓存
            redisUtils.set(key, queryUserVo.getImgUrl());
        }
        return i;
    }


    public void flushUserInfo(String token, Long userId) throws Exception {
        CsUser csUser = restCsUserClient.getCsUserById(userId);
        CsUserVO csUserVO = new CsUserVO();
        BeanUtils.copyProperties(csUser, csUserVO);
        csUserVO.setUserId(csUser.getId());
        // 查询用户头像
        List<CsImage> logo = restCsImageClient.queryCsImageList(csUser.getId(), 0, 0); // 等常量，等常量，等常量，等常量，等常量，等常量，等常量，等常量，等常量，
        // 如果用户指定了头像，拷贝用户头像信息到DTO
        if (EmptyUtils.isNotEmpty(logo)) {
            csUserVO.setImageId(logo.get(0).getId());
            csUserVO.setImgUrl(logo.get(0).getImgUrl());
        }

    }

    public void save(String token, CsUserVO user) throws Exception {
        String tokenKey = Constants.USER_TOKEN_PREFIX + user.getUserId();
        String tokenValue = null;
        // 检查是否为会话有效期内的重复登录，若是则首先删除之前缓存的用户数据和token，原登录失效
        if ((tokenValue = (String) redisUtils.get(tokenKey)) != null) {
            redisUtils.delete(tokenValue);
        }
        // 缓存用户token
        redisUtils.set(tokenKey, Constants.Redis_Expire.SESSION_TIMEOUT, token);
        // 缓存用户信息
        redisUtils.set(token, Constants.Redis_Expire.SESSION_TIMEOUT, JSON.toJSONString(user));
    }
}
